<template>
  <div class="container">
    <div id="particles-js" style="position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: -1;"></div>
    <div class="container" :class="{ 'right-panel-active': isSignUpActive }" ref="formContainerRef" :model="loginForm">
      <div class="form-container"
           :class="{ 'sign-up-container': isSignUpActive, 'sign-in-container': !isSignUpActive }">
        <!-- 用户注册 -->
        <el-form v-if="isSignUpActive" @submit.prevent="submitForm('registerForm')" ref="registerFormRef"
                 :model="registerForm" label-width="80px" :rules="RegisterFormRules" class="register-form">
          <h1>注册</h1>
          <el-form-item label="用户名" prop="account" class="register-form-item">
            <el-input type="text" placeholder="请输入账号" v-model="registerForm.account" required class="register-input"/>
          </el-form-item>
          <el-form-item label="密码" prop="password" class="register-form-item">
            <el-input type="password" placeholder="请输入密码" v-model="registerForm.password" required class="register-input"/>
          </el-form-item>
          <el-form-item label="确认密码" prop="password2" class="register-form-item">
            <el-input type="password" placeholder="请确认密码" v-model="registerForm.password2" required class="register-input"/>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" class="register-form-item">
            <el-input type="text" placeholder="请输入邮箱" v-model="registerForm.email" required class="register-input"/>
          </el-form-item>
          <!-- 注册表单验证码项 -->
          <el-form-item label="验证码" prop="code" class="register-form-item">
            <div class="code-wrap">
              <el-input type="text" placeholder="请输入验证码" v-model="registerForm.code" required class="register-input code-input"/>
            </div>
          </el-form-item>
          <el-form-item class="register-submit-item code-register-item">
            <el-button :loading="registerLoading" :disabled="registerLoading" @click="submitForm('registerForm')" class="register-submit-btn" type="primary">注册</el-button>
            <el-button type="text" @click="getCode(registerForm)" class="register-code-btn">获取验证码</el-button>
          </el-form-item>
        </el-form>

        <!-- 邮箱号登录（完全保留优化后代码） -->
                <el-form v-else-if="ifPhoneLogin" @submit.prevent="plogin" ref="PLoginFormRef" 
                         :model="PLoginForm" label-width="0" :rules="PLoginFormRules"
                         class="phone-login-form">
                  <h2>邮箱号登录</h2>
                  <el-form-item prop="phoneNumber" class="phone-form-item">
                    <el-input 
                      type="text" 
                      placeholder="输入邮箱号:" 
                      v-model="PLoginForm.email" 
                      required 
                      class="phone-input"
                    />
                  </el-form-item>
                  <el-form-item prop="code" class="phone-form-item code-item">
                    <el-input 
                      type="text" 
                      placeholder="输入验证码:" 
                      v-model="PLoginForm.code" 
                      required 
                      class="phone-input"
                    />
                    <el-button type="text" @click="getCode(PLoginForm)" class="code-btn">获取验证码</el-button>
                  </el-form-item>
                  <div class="login-options phone-options">
                    <input type="checkbox" id="remember-me-phone">
                    <label for="remember-me-phone">记住邮箱号?</label>
                  </div>
                  <el-form-item class="phone-form-item">
                    <button @click="plogin()" class="phone-login-btn">登录</button><br>
                    <a @click="changeLog(false)" class="switch-link">密码登录</a>
                  </el-form-item>
                </el-form>


        <!-- 密码登录 -->
        <el-form v-else ref="loginFormRef" 
          :model="loginForm" label-width="120px" :rules="LoginFormRules" @submit.prevent="LoginSubmitForm"
          style="margin-top: 60px;">
                <h2>密码登录</h2>
                <el-input
                  v-model="loginForm.account"
                  placeholder="请输入用户名"
                  tabindex="1"
                  type="text"
                  required
                  style="width: 80%; height: 50px; margin-bottom: 20px; margin-left: 20px;"
                >
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
                <el-input
                  :key="passwordType"
                  ref="password"
                  v-model="loginForm.password"
                  :type="passwordType"
                  tabindex="2"
                  placeholder="请输入密码"
                  required
                  style="width: 80%; height: 50px; margin-bottom: 20px; margin-left: 20px;"
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                  </el-input >
                <span class="show-pwd" @click="showPwd">
                  <el-icon v-if="passwordType === 'password'">
                    <Hide />
                  </el-icon>
                  <el-icon v-else>
                    <View />
                  </el-icon>
                </span>
                <div class="login-options" style="margin-left: 20px;">
                  <input type="checkbox" id="remember-me-pwd">
                  <label for="remember-me-pwd">记住密码?</label>
                  <router-link :to="{name:'忘记密码'}" style="color: #0e0202; margin-left: auto; display: block; text-align: right;">忘记密码</router-link>
                </div>
                <el-form-item>
                  <button type="submit">登录</button><br>
                  <a style="display: block; text-align: center; margin-top: 10px; color: black;" @click="changeLog(true)">邮箱号登录</a>
                </el-form-item>
        </el-form>
      </div>

      <div class="overlay-container">
        <div class="overlay">
          <div class="overlay-panel overlay-left" @click="toggleForm(false)">
            <h1 class="hlefttext">已有</h1>
            <h1 class="hlefttext">&nbsp;&nbsp;账号？</h1>
            <p class="plefttext">&nbsp;&nbsp;&nbsp;点我登陆!</p>
          </div>
          <div class="overlay-panel overlay-right" @click="toggleForm(true)">
            <h1 class="hrighttext">没有</h1>
            <h1 class="hrighttext">&nbsp;&nbsp;账户？</h1>
            <p class="prighttext">&nbsp;&nbsp;&nbsp;&nbsp;点我，加入我们的世界！</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { get, post } from '../../utils/axios.js'
import { ElMessage, ElButton, ElForm, ElFormItem, ElInput, ElLink } from 'element-plus'
import { useRouter } from 'vue-router'
import { User } from '@element-plus/icons-vue'
import { Hide, View } from '@element-plus/icons-vue'
import { Lock } from '@element-plus/icons-vue'

const router = useRouter()

const drawer = ref(false)
const innerDrawer = ref(false)
const isSignUpActive = ref(false)
const ifPhoneLogin = ref(false)
const phoneNumber = ref('')
const code = ref('')
const password = ref(null);
const passwordType = ref('password')
const showPwd = () => {
  passwordType.value = passwordType.value === "password" ? "text" : "password";
  nextTick(() => {
    password.value?.focus();
  });
};

const loginForm = reactive({
  account: '',
  password: ''
})
const PLoginForm = reactive({
  email: '',
  code: ''
})
const registerForm = reactive({
  account: '',
  password: '',
  password2: '',
  email: '',
  code: ''
})

const LoginFormRules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}
const emailPattern = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
const PLoginFormRules = {
  email: [
    { required: true, message: '请输入邮箱账号', trigger: 'blur' },
    { pattern: emailPattern, message: '请输入正确的邮箱账号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码必须为6位', trigger: 'blur' }
  ]
}
const RegisterFormRules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码必须大于等于6位', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { min: 6, message: '密码必须大于等于6位', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱账号', trigger: 'blur' },
    { pattern: emailPattern, message: '请输入正确的邮箱账号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码必须为6位数字', trigger: 'blur' }
  ]
}

const formContainerRef = ref()
const loginFormRef = ref()
const registerFormRef = ref()
const PLoginFormRef = ref()
const registerLoading = ref(false)

function toggleForm(isSignUp = !isSignUpActive.value) {
  isSignUpActive.value = isSignUp
}
function changeLog(isSignUp) {
  ifPhoneLogin.value = isSignUp
}

function getCode(form) {
  if (!form.email) {
    ElMessage.warning('请先输入邮箱账号')
    return
  }

  post(
    '/sc/employee/sendEmailCode',
    { email: form.email },
    (res) => {
      if (res.state === "success" ) {
        ElMessage.success('验证码发送成功！')
      } else {
        ElMessage.error(res.message || '验证码发送失败，请重试')
      }
    },
    (err) => {
      ElMessage.error('网络异常，请检查网络连接')
    }
  )
}

function LoginSubmitForm() {
  if (!loginFormRef.value) return

  loginFormRef.value.validate((valid) => {
    if (valid) {
      post(
        '/sc/employee/login',
        {
          account: loginForm.account,
          password: loginForm.password
        },
        (res) => {
          if (res.status === 1) {
            ElMessage.success(res.message || '登录成功！')
            window.sessionStorage.setItem('loginState', JSON.stringify(res.data))
            window.sessionStorage.setItem('account', loginForm.account)
            router.push({ path: '/home' })
          } else {
            ElMessage.error(res.message || '账号或密码错误，请重试')
          }
        },
        (err) => {
          ElMessage.error('登录请求失败，请检查网络')
        }
      )
    } else {
      ElMessage.error('请完善登录信息并确保格式正确')
      return false
    }
  })
}

function plogin() {
  if (!PLoginFormRef.value) return

  PLoginFormRef.value.validate((valid) => {
    if (valid) {
      post(
        '/sc/employee/loginByEmail',
        PLoginForm,
        (res) => {
          if (res.state === "success" ) {
            ElMessage.success('登录成功！')
            window.sessionStorage.setItem('loginState', JSON.stringify(res.data || {}))
            window.sessionStorage.setItem('account', PLoginForm.email)
            router.push({ path: '/home' })
          } else {
            console.log(res);
            ElMessage.error(res.message || '登录失败，请检查验证码')
          }
        },
        (err) => {
          ElMessage.error('登录请求失败，请检查网络')
        }
      )
    } else {
      ElMessage.error('请完善邮箱账号和验证码信息')
      return false
    }
  })
}

function register() {
  if (registerLoading.value) return;
  registerLoading.value = true;
  const registerData = {
    name: '11',
    position: '超级管理员',
    status: '在职',
    account: registerForm.account,
    password: registerForm.password,
    email: registerForm.email
  }

  post(
    '/sc/employee/add',
    registerData,
    (res) => {
      if (res.status === 1) {
              ElMessage.success('注册并验证成功！请登录')
              Object.assign(registerForm, { account: '', password: '', password2: '', email: '', code: '' })
              toggleForm(false)
      } else {
        registerLoading.value = false;
        ElMessage.error(res.message || '注册失败，请重试')
      }
    },
    (err) => {
      registerLoading.value = false;
      ElMessage.error('注册请求失败，请检查网络')
    }
  )
}

function submitForm(formName) {
  let formRef = null
  if (formName === 'registerForm') formRef = registerFormRef
  if (!formRef || !formRef.value) return

  formRef.value.validate((valid) => {
    if (valid) {
      register()
    } else {
      ElMessage.error('表单验证失败，请检查信息格式')
      return false
    }
  })
}
</script>

<style>
/* 全局样式 */
body {
  font-family: 'Montserrat', sans-serif;
  /*background-image: url("../../assets/beij.png");*/
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
}

h1 {
  font-weight: bold;
  margin: 0 auto 30px;
  width: 100%;
  text-align: center;
  font-size: 1.8rem;
}

h2 {
  font-weight: bold;
  margin: 0 auto 20px;
  width: 100%;
  text-align: center;
  font-size: 2rem;
}

.container {
  background: rgba(74, 161, 168, 0.57);
  border-radius: 10px;
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 768px;
  max-width: 100%;
  min-height: 550px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-left: 0;
}

.form-container {
  width: 50%;
  position: absolute;
  top: 0;
  height: 100%;
  transition: all 0.6s ease-in-out;
  padding: 40px 20px;
  box-sizing: border-box;
}

/* 注册表单样式 */
.register-form {
  width: 100%;
  padding: 0 60px;
  box-sizing: border-box;
  margin-top: 20px;
}

.register-form-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  width: 100%;
}

.register-input {
  width: 100%;
  height: 32px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
  box-sizing: border-box;
  outline: none;
  transition: border-color 0.2s;
}

.register-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.code-register-item {
  display: flex;
  align-items: center;
  padding: 0 !important;
  margin-bottom: 15px !important;
}

.code-wrap {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 8px;
}

.code-input {
  flex: 1;
  height: 32px !important;
  line-height: 32px !important;
}

.register-code-btn {
  height: 32px !important;
  line-height: 32px !important;
  padding: 0 12px !important;
  font-size: 14px !important;
  color: #409eff !important;
  background: transparent !important;
  border: none !important;
}

.register-code-btn:hover {
  color: #2690ff !important;
  background: transparent !important;
}

.register-submit-item {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.register-submit-btn {
  width: auto;
  padding: 8px 30px;
  border-radius: 20px;
  border: 1px solid #297cce;
  background: #297cce;
  color: #ffffff;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: 1px;
  text-transform: uppercase;
  transition: all 0.3s ease;
  cursor: pointer;
}

.register-submit-btn:hover {
  background-color: #2228c2;
  border-color: #ff96b9;
  transform: translateY(-2px);
}

/* 手机号登录样式（核心修改） */
.phone-login-form {
  margin-top: 60px;
  padding: 0 50px;
  box-sizing: border-box;
}

.phone-form-item {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.phone-input {
  width: 100%;
  height: 50px;
  margin: 0 auto;
}

/* 验证码按钮与登录按钮同行布局 */
.combined-row {
  margin-bottom: 20px !important;
  padding: 0 !important;
}

.code-and-login {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.inline-code-item {
  flex: 1;
  display: flex;
  align-items: center;
  margin: 0 !important;
  padding: 0 !important;
}

.inline-code-item .code-input {
  flex: 1;
  margin-right: 10px;
}

.inline-login-btn {
  width: 100px;
  padding: 0;
  height: 50px;
  white-space: nowrap;
}

.switch-item {
  margin-top: 0 !important;
}

.code-btn {
  height: 50px !important;
  line-height: 50px !important;
  padding: 0 12px !important;
  white-space: nowrap;
}

.phone-options {
  margin: 0 auto 10px;
  width: 100%;
  text-align: left;
}

.phone-login-btn {
  margin: 0 auto;
  display: block;
}

.switch-link {
  display: block;
  text-align: center;
  margin-top: 10px;
  color: black;
  cursor: pointer;
}

/* 密码登录样式 */
.login-options button {
  margin-left: 1px;
  height: 40px;
  width: 100px;
  white-space: nowrap;
  text-align: center;
  font-weight: 100;
  font-size: 15px;
  padding: 5px;
}

.login-options input[type="checkbox"] {
  margin-right: 5px;
}

.login-options label {
  font-size: 14px;
  margin-right: 54px;
}

.forget-password {
  margin-left: 10px;
  font-size: 12px;
  text-decoration: none;
  color: #0e0202;
  border: 1px solid rgba(14, 2, 2, 0);
  border-radius: 5px;
  cursor: pointer;
}

.forget-password:hover {
  background-color: #f0f0f0;
}

.show-pwd {
  position: relative;
  left: -30px;
  cursor: pointer;
}

/* 覆盖层样式 */
.el-form-item {
  margin-bottom: 20px;
}

.sign-in-container {
  left: 0;
  width: 50%;
  z-index: 2;
}

.sign-up-container {
  left: 0;
  width: 50%;
  opacity: 0;
  z-index: 1;
}

.container.right-panel-active .sign-in-container {
  transform: translateX(100%);
}

.container.right-panel-active .sign-up-container {
  transform: translateX(100%);
  opacity: 1;
  z-index: 5;
  animation: show 0.6s;
}

@keyframes show {
  0%, 49.99% {
    opacity: 0;
    z-index: 1;
  }
  50%, 100% {
    opacity: 1;
    z-index: 5;
  }
}

input {
  background: #eee;
  border: none;
  padding: 12px 15px;
  margin: 8px 0;
  border-radius: 10px;
  margin-left: 0;
}

input[type="text"],
input[type="password"] {
  width: 100%;
}

button {
  border-radius: 20px;
  border: 1px solid #297cce;
  background: #297cce;
  color: #ffffff;
  font-size: 15px;
  font-weight: bold;
  padding: 12px 45px;
  letter-spacing: 1px;
  text-transform: uppercase;
  margin-top: 5px;
  transition: transform 80ms ease-in;
  cursor: pointer;
}

button:active {
  transform: scale(0.95);
}

button:focus {
  outline: none;
}

button:hover {
  background-color: #2228c2;
  border-color: #ff96b9;
}

.overlay-container {
  position: absolute;
  top: 0;
  left: 50%;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: transform 0.6s ease-in-out;
  z-index: 100;
}

.container.right-panel-active .overlay-container {
  transform: translateX(-100%);
}

.overlay {
  background: #febfce;
  background: linear-gradient(to right, #ff96b9, #ffb8f3);
  color: #fff;
  position: relative;
  left: -100%;
  height: 100%;
  width: 200%;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
}

.container.right-panel-active .overlay {
  transform: translateX(50%);
}

.overlay-panel {
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 40px;
  text-align: center;
  top: 0;
  height: 100%;
  width: 50%;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
}

.overlay-left {
  background-image: url("../../assets/img_1.jpg");
  background-size: cover;
  transform: translateX(-20%);
}

.container.right-panel-active .overlay-left {
  transform: translateX(0);
}

.overlay-right {
  background-image: url("../../assets/img_2.jpg");
  background-size: cover;
  right: 0;
  transform: translateX(0);
}

.container.right-panel-active .overlay-right {
  transform: translateX(20%);
}

.hlefttext {
  margin-right: 125px;
  font-size: 45px;
}

.plefttext {
  font-size: 25px;
  margin-right: 100px;
}

.hrighttext {
  margin-right: 50px;
  font-size: 45px;
}

.prighttext {
  font-size: 25px;
}

p {
  font-size: 14px;
  font-weight: 100;
  line-height: 20px;
  letter-spacing: 0.5px;
  margin: 20px 0 30px;
}
</style>
